#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextFormat>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    qDebug() << "GUI:" << QThread::currentThread();

        initControlProcess();

        serialServer = new SerialServer();
        serialThread = new QThread(this);
        serialServer->moveToThread(serialThread);   // 将 SerialServer 对象移动到新线程
        connect(serialServer, &SerialServer::serialDataReceivedReady, this, &MainWindow::onSerialDataReceived);
        serialThread->start();  // 启动线程

        connect(serialThread, &QThread::finished, serialServer, &QObject::deleteLater);

        connect(ui->plainTextEdit_recv, &QPlainTextEdit::textChanged, this, &MainWindow::updateButtonState_cleanrecv);
        connect(ui->pushButton_cleanrecv, &QPushButton::clicked, this, &MainWindow::on_pushButton_cleanrecv_clicked);
        connect(ui->plainTextEdit_send, &QPlainTextEdit::textChanged, this, &MainWindow::updateButtonState_cleansend);
        connect(ui->pushButton_cleansend, &QPushButton::clicked, this, &MainWindow::on_pushButton_cleansend_clicked);

}

MainWindow::~MainWindow()
{
    serialThread->quit();
    serialThread->wait();
    delete serialServer;  // 删除 serialServer 对象
    delete ui;
}

void MainWindow::initControlProcess()
{
    FillSerialControl();

        ui->label_ConnectState->setText("未连接");
        ui->label_RS->setText("UTF-8");

        ui->pushButton_cleanrecv->setEnabled(false);
        ui->pushButton_cleansend->setEnabled(false);

        updateControlState(false);

}

void MainWindow::FillSerialControl()
{
    // 填充波特率
       for (int i = 0; i < 8; ++i) {
           ui->comboBox_Baud->addItem(QString::number(use_BAUD[i]));
       }

       // 填充数据位
       QStringList dataBitsLabels = {"5", "6", "7", "8"};
       for (int i = 0; i < 4; ++i) {
           ui->comboBox_Databits->addItem(dataBitsLabels[i], use_DATABITS[i]);
       }

       // 填充校验位
       QStringList parityLabels = {"No Parity", "Even Parity", "Odd Parity", "Space Parity", "Mark Parity"};
       for (int i = 0; i < 5; ++i) {
           ui->comboBox_Parity->addItem(parityLabels[i], use_PARITY[i]);
       }

       // 填充停止位
       QStringList stopBitsLabels = {"1", "1.5", "2", "Unknown"};
       for (int i = 0; i < 4; ++i) {
           ui->comboBox_Stopbits->addItem(stopBitsLabels[i], use_STOPBITS[i]);
       }

       // 自动获取可用串口号
       ui->comboBox_Com->clear();
       const auto ports = QSerialPortInfo::availablePorts();
       for (const QSerialPortInfo &portInfo : ports) {
           ui->comboBox_Com->addItem(portInfo.portName());
       }

       // 如果没有找到可用的串口
       if (ui->comboBox_Com->count() == 0) {
           ui->comboBox_Com->addItem(QStringLiteral("无可用串口"));
       }

}

void MainWindow::updateControlState(bool flag)
{
    QList<QPushButton*> buttons = {ui->pushButton_disConnect,ui->pushButton_send};

        for (QPushButton* button : buttons) {
            button->setEnabled(flag);
        }
}

void MainWindow::displaySendData(const QByteArray &data)
{
    QString strSend = formatDataBasedOnHexCheck(data);
    appendColoredText("<SEND>: ", strSend, Qt::blue);
}

void MainWindow::appendColoredText(const QString &prefix, const QString &data, const QColor &color)
{
    QDateTime dateTime = QDateTime::currentDateTime();
        QString s_time = dateTime.toString("hh:mm:ss.zzz"); // 获取当前时间

        QMetaObject::invokeMethod(this, [=] {
            QTextCursor cursor(ui->plainTextEdit_recv->textCursor());
            cursor.movePosition(QTextCursor::End);
            ui->plainTextEdit_recv->setTextCursor(cursor);

            QTextCharFormat format;
            format.setForeground(color); // 设置传入的颜色

            cursor.insertText(s_time + prefix, format); // 插入时间戳和前缀
            format.setForeground(Qt::black); // 恢复为黑色字体（数据部分）
            cursor.insertText(data + "\n", format);
        }, Qt::QueuedConnection);

}

QString MainWindow::formatDataBasedOnHexCheck(const QByteArray &data)
{
    QString formattedData;

        if (ui->checkBox_Hex->isChecked()) {
            formattedData = data.toHex(' ').toUpper(); // hex 格式
            ui->label_RS->setText("HEX");
        } else {
            formattedData = QString::fromUtf8(data); // 原始数据格式
            ui->label_RS->setText("UTF-8");
        }
        return formattedData;

}


void MainWindow::on_pushButton_Connect_clicked()
{
    QString portName = ui->comboBox_Com->currentText();
       unsigned int baudRate = ui->comboBox_Baud->currentText().toUInt();
       QSerialPort::DataBits dataBits = static_cast<QSerialPort::DataBits>(ui->comboBox_Databits->currentData().toInt());
       QSerialPort::Parity parity = static_cast<QSerialPort::Parity>(ui->comboBox_Parity->currentData().toInt());
       QSerialPort::StopBits stopBits = static_cast<QSerialPort::StopBits>(ui->comboBox_Stopbits->currentData().toInt());

       QMetaObject::invokeMethod(serialServer, [=]{
           if (serialServer->openSerialPort(portName, baudRate, dataBits, parity, stopBits)) {
               qDebug() << "串口打开成功:" << portName << baudRate << dataBits << stopBits << parity;

               // 更新UI在主线程中完成
               QMetaObject::invokeMethod(this, [=] {
                   ui->label_ConnectState->setText("已连接");
                   ui->pushButton_Connect->setEnabled(false);
                   updateControlState(true);
               }, Qt::QueuedConnection);
           } else {
               qDebug() << "串口打开失败,请检查串口是否被占用或配置是否正确:" << portName << baudRate << dataBits << stopBits << parity;
           }
       }, Qt::QueuedConnection);


}

void MainWindow::on_pushButton_update_clicked()
{

}

void MainWindow::on_pushButton_disConnect_clicked()
{
    QMetaObject::invokeMethod(serialServer, [=] {
        serialServer->closeSerialPort();
    }, Qt::QueuedConnection);

    qDebug() << "断开串口连接";
    ui->label_ConnectState->setText("未连接");
    ui->pushButton_Connect->setEnabled(true);
    updateControlState(false);

}

void MainWindow::on_pushButton_cleanrecv_clicked()
{
    if (ui->plainTextEdit_recv->toPlainText().isEmpty()) {
        ui->pushButton_cleanrecv->setEnabled(false);
    } else {
        ui->plainTextEdit_recv->clear();
    }

}



void MainWindow::on_pushButton_send_clicked()
{
    QString text = ui->plainTextEdit_send->toPlainText();
       QByteArray data = text.toUtf8();

       if (!text.isEmpty()) {

           // 发送数据的部分放入serialServer的线程
           QMetaObject::invokeMethod(serialServer, [=] {
               serialServer->SendSerialData(data);
           }, Qt::QueuedConnection);

           // UI更新部分在主线程中执行
           QDateTime dateTime = QDateTime::currentDateTime();
           QString s_time = dateTime.toString("hh:mm:ss.zzz");
           QString strSend = QString(data);

           appendColoredText("<SEND>: ", strSend, Qt::blue);

       } else {
           qDebug() << "发送数据不可为空";
           ui->statusbar->showMessage("发送数据不可为空.", 1500);
       }
}

void MainWindow::on_pushButton_cleansend_clicked()
{
    ui->plainTextEdit_send->clear();

        if (ui->plainTextEdit_send->toPlainText().isEmpty()) {
            ui->pushButton_cleansend->setEnabled(false);
        } else {
            ui->plainTextEdit_send->clear();
        }

}

void MainWindow::on_checkBox_Hex_stateChanged(int arg1)
{
    if (ui->checkBox_Hex->isChecked()) {
            ui->label_RS->setText("HEX");
        } else {
            ui->label_RS->setText("UTF8");
    }
}

void MainWindow::onSerialDataReceived(const QByteArray &data)
{
    QString strRecv = formatDataBasedOnHexCheck(data);
    appendColoredText("<RECV>: ", strRecv, Qt::green);
}

void MainWindow::updateButtonState_cleanrecv()
{
    ui->pushButton_cleanrecv->setEnabled(!ui->plainTextEdit_recv->toPlainText().isEmpty());
}

void MainWindow::updateButtonState_cleansend()
{
    ui->pushButton_cleansend->setEnabled(!ui->plainTextEdit_send->toPlainText().isEmpty());
}
